﻿using DevExpress.XtraEditors.Controls;
using ExRichTextBox;
using RecruitStudents.Client.BLL;
using RecruitStudents.Client.Examinee;
using RecruitStudents.Utility;
using RecruitStudents.Utility.Const;
using RecruitStudents.Utility.Helper;
using RecruitStudents.Utility.Model;
using RecruitStudents.Utility.Push;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RecruitStudents.Client.Consult
{
    public partial class ConsultForm_List : BaseForm
    {
        ServiceConsult service = new ServiceConsult();
        private int selectStart1 = 0;
        private string strMsgID;
        private string strUsersNickName;
        //系统是否运行
        private bool isRun = false;//是否有数据
        private int imgIconIndex = 0;
        public ConsultForm_List()
        {
            InitializeComponent();
        }

        private void ConsultForm_List_Load(object sender, EventArgs e)
        {
            BindConsultResorce();
            strMsgID = "";
            strUsersNickName = "";
            timer_ReadID.Enabled = true;
            BoundMsgList(string.Empty);
        }
        #region 绑定来源方式
        private void BindConsultResorce()
        {
            this.ConsultResorce.Properties.NullText = "";
            //this.ConsultResorce.Properties.Columns.Add(new LookUpColumnInfo("Key", 30, "来源编号"));
            this.ConsultResorce.Properties.Columns.Add(new LookUpColumnInfo("Value", 55, "来源"));
            this.ConsultResorce.Properties.DataSource = ConstAppConfig.DicConsultResorceType.ToList();
            this.ConsultResorce.Properties.DisplayMember = "Value";
            this.ConsultResorce.Properties.ValueMember = "Key";
        }
        #endregion

        #region 绑定数据表格 绑定待回复区
        private void BoundMsgList(string strCondition)
        {
            DataTable dt = service.GetWaitResponseProblemTable(string.Empty, checkIsTop.Checked.ToSafeString().ToLower(), ckStudent.Checked.ToSafeString().ToLower(), ckIsFee.Checked.ToSafeString().ToLower(), ConsultResorce.EditValue.ToSafeString());

            int rowHandle = 0;
            if (dt != null)
            {
                dt.Columns.Add("strNO", typeof(int));
                for (int i = 1; i <= dt.Rows.Count; i++)
                {
                    dt.Rows[i - 1]["strNO"] = i;
                    if (dt.Rows[i - 1]["ID"].ToSafeString() == strMsgID)
                    {
                        rowHandle = i - 1;
                    }
                }
                if (dt.Rows.Count > 0 && strMsgID == "")
                {
                    strMsgID = dt.Rows[0]["ID"].ToSafeString();
                    strUsersNickName = dt.Rows[0]["UsersNickName"].ToSafeString();
                    BoundReplyList();
                }
                this.isRun = true;//开始闪烁
            }
            else
            {
                this.isRun = false;//取消闪烁
            }
            dgvDisplayMsg.DataSource = dt;
            if (strMsgID == "")
            {
                this.gridView2.FocusedRowHandle = -1;
                this.gridView2.ClearSelection();
            }
            else
            {
                this.gridView2.FocusedRowHandle = rowHandle;
                gridView2.SelectRow(rowHandle);
            }
        }
        #endregion

        #region rtf转换为html
        /// <summary>
        /// rtf转换为html
        /// </summary>
        /// <param name="rich"></param>
        /// <returns></returns>
        public static string GetHtml(string rtf)
        {
            SautinSoft.RtfToHtml r = new SautinSoft.RtfToHtml();
            r.OutputFormat = SautinSoft.eOutputFormat.HTML_401;
            r.ImageStyle.IncludeImageInHtml = true; //To save images inside HTML as binary data specify this property to 'true'

            r.ImageStyle.ImageFolder = @"D:\";
            r.ImageStyle.ImageSubFolder = "images";
            r.ImageStyle.ImageFileName = "picture";

            string html = r.ConvertString(rtf);

            int index = 0;

            index = html.IndexOf("<body>") + 6;

            html = html.Substring(index, html.Length - index);

            html.Replace("</body>", "");
            html.Replace("</html>", "");

            return html;
        }
        #endregion

        #region 回复区展示
        private void BoundReplyList()
        {
            if (strMsgID.Trim() != "")
            {
                string strCondition = strMsgID.Trim();
                DataTable dt = service.GetReplyAreaShow(strCondition);

                string strTopicID = "";
                bool flagNewTop = true;
                selectStart1 = 0;
                richHistory.Clear();

                foreach (DataRow dr in dt.Rows)
                {
                    if (strTopicID != dr["ID"].ToString().Trim())
                    {
                        strTopicID = dr["ID"].ToString().Trim();
                        flagNewTop = true;

                        //新问题的分隔符
                        AppendSeparate();

                        string Title = "";

                        if (dr["State"].ToString().Trim() == "1")
                            Title = dr["CreateDate"].ToString().Trim() + "  " + dr["UsersNickName"].ToString().Trim() + "\n" + dr["ConsultTitle"].ToString().Trim();
                        else
                            Title = dr["CreateDate"].ToString().Trim() + "  " + dr["UsersNickName"].ToString().Trim() + "  [已删除] \n" + dr["ConsultTitle"].ToString().Trim();

                        Append(Title, "T");

                        if (strMsgID.Trim() == dr["ID"].ToString().Trim())
                        {
                            string MsgQ = dr["CreateDate"].ToString().Trim() + "  【" + dr["UsersNickName"].ToString().Trim() + "】\n" + dr["ConsultContent"].ToString().Trim();
                            Append(MsgQ, "Q");

                            flagNewTop = false;
                        }
                        else
                        {
                            string MsgQ = dr["CreateDate"].ToString().Trim() + "  【" + dr["UsersNickName"].ToString().Trim() + "】\n" + dr["ConsultContent"].ToString().Trim();
                            Append(MsgQ, "QQ");

                            flagNewTop = false;
                        }
                    }
                    else
                    {
                        if (strMsgID.Trim() == dr["ID"].ToString().Trim())
                        {
                            string MsgTitleReply = dr["RCreateDate"].ToString().Trim() + "  【" + dr["RConsultUsersNickName"].ToString().Trim() + "】";
                            string MsgA = dr["RConsultContent"].ToString().Trim();

                            if (dr["UsersNickName"].ToString().Trim().ToUpper() == dr["RConsultUsersNickName"].ToString().Trim().ToUpper())
                            {
                                Append(MsgTitleReply, "QT");
                                Append(MsgA, "Q");
                            }
                            else
                            {
                                AppendTitleReply(MsgTitleReply);
                                Append(MsgA, "MY");
                            }
                        }
                        else
                        {
                            string MsgTitleReply = dr["RCreateDate"].ToString().Trim() + "  【" + dr["RConsultUsersNickName"].ToString().Trim() + "】";
                            string MsgA = dr["RConsultContent"].ToString().Trim();

                            if (dr["UsersNickName"].ToString().Trim() == dr["RConsultUsersNickName"].ToString().Trim())
                            {
                                Append(MsgTitleReply, "QQT");
                                Append(MsgA, "QQ");
                            }
                            else
                            {
                                AppendTitleReply(MsgTitleReply);
                                Append(MsgA, "A");
                            }
                        }
                    }
                }

                Resh();
            }
        }

        private void Append(string Msg, string strQA)
        {
            if (strQA == "T") //Title
            {
                selectStart1 = richHistory.TextLength;
                richHistory.AppendText(Msg + Environment.NewLine + Environment.NewLine);
                richHistory.Select(selectStart1, richHistory.TextLength - 1);
                richHistory.SelectionColor = Color.Black;
                richHistory.SelectionIndent = 0;
                richHistory.SelectionRightIndent = 0;
                richHistory.SelectionBackColor = ColorTranslator.FromHtml("#C5D9F1");  //蓝色
            }
            else if (strQA == "Q") //本问题
            {
                selectStart1 = richHistory.TextLength;
                richHistory.AppendText(Msg + Environment.NewLine + Environment.NewLine);
                richHistory.Select(selectStart1, richHistory.TextLength - 1);
                richHistory.SelectionColor = Color.Black;
                richHistory.SelectionIndent = 0;
                richHistory.SelectionRightIndent = 0;
                richHistory.SelectionBackColor = ColorTranslator.FromHtml("#AECA72");  //绿色
            }
            else if (strQA == "QQ") //不是本问题
            {
                selectStart1 = richHistory.TextLength;
                richHistory.AppendText(Msg + Environment.NewLine + Environment.NewLine);
                richHistory.Select(selectStart1, richHistory.TextLength - 1);
                richHistory.SelectionColor = Color.Black;
                richHistory.SelectionIndent = 0;
                richHistory.SelectionRightIndent = 0;
                richHistory.SelectionBackColor = ColorTranslator.FromHtml("#E8E8E8");  //灰色
            }
            else if (strQA == "A")//本问题 提问的问题 已经回复
            {
                richHistory.AppendRtf(Msg);
                richHistory.AppendText(Environment.NewLine);
            }
            else if (strQA == "QT")//提问问题的标题
            {
                selectStart1 = richHistory.TextLength;
                richHistory.AppendText(Msg + Environment.NewLine);
                richHistory.Select(selectStart1, richHistory.TextLength - 1);
                richHistory.SelectionColor = Color.Black;
                richHistory.SelectionIndent = 0;
                richHistory.SelectionRightIndent = 0;
                richHistory.SelectionBackColor = ColorTranslator.FromHtml("#AECA72");  //绿色
            }
            else if (strQA == "QQT")//提问问题的标题
            {
                selectStart1 = richHistory.TextLength;
                richHistory.AppendText(Msg + Environment.NewLine);
                richHistory.Select(selectStart1, richHistory.TextLength - 1);
                richHistory.SelectionColor = Color.Black;
                richHistory.SelectionIndent = 0;
                richHistory.SelectionRightIndent = 0;
                richHistory.SelectionBackColor = ColorTranslator.FromHtml("#E8E8E8");  //灰色
            }
            else
            {
                richHistory.AppendRtf(Msg);
                richHistory.AppendText(Environment.NewLine);
            }
        }

        private void AppendSeparate()
        {
            string Msg = "**********************************************************************************************************" + Environment.NewLine;
            richHistory.AppendTextAsRtf(Msg, new Font(this.Font, FontStyle.Regular), RtfColor.Green, RtfColor.Yellow);
        }

        private void AppendTitleReply(string Msg)
        {
            selectStart1 = richHistory.TextLength;
            richHistory.AppendText(Msg + Environment.NewLine);
            richHistory.Select(selectStart1, richHistory.TextLength - 1);
            richHistory.SelectionColor = Color.Black;
            richHistory.SelectionBackColor = ColorTranslator.FromHtml("#F7B940");  //橙色
        }

        private void Resh()
        {
            richHistory.SelectionStart = richHistory.Text.Length;
            richHistory.ScrollToCaret();
        }
        #endregion

        private void Method()
        {
            DataTable dt = service.GetConsultTitleByID(strMsgID);
            if (dt != null && dt.Rows.Count > 0)
            {
                string strUserType = dt.Rows[0]["UserType"].ToSafeString();
                string strNickName = dt.Rows[0]["NickName"].ToSafeString();
                if (strUserType == "考生")
                {
                    #region 推送消息
                    PushHelper objJPush = new PushHelper();
                    TB_ConsultTitle objTitle = new TB_ConsultTitle();
                    TB_ConsultReply objReply = new TB_ConsultReply();
                    objTitle.UsersID = strNickName;
                    objTitle.ID = strMsgID;
                    objTitle.ConsultTitle = "咨询互动回复";
                    objTitle.TypeID = ConsultType.ZX;
                    objJPush.Push(objTitle, objReply);
                    #endregion
                }
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (strMsgID.Trim() == "")
            {
                DevHelper.ShowInfoMessageBox("请选择需要回复的问题！");
                return;
            }
            if (richSend.Text.Trim() == "")
            {
                DevHelper.ShowInfoMessageBox("请填写回复信息！");
                return;
            }
            else
            {
                string strSend = GetHtml(richSend.Rtf);
                try
                {
                    bool flag = service.SaveConsultReply_UpdateConsultTitle(strMsgID, richSend.Rtf.Replace("'", "''"), SessionerHelper.UserName, strSend.Replace("'", "''"), SessionerHelper.UserID, ConsultType.ZX);
                    Thread thread = new Thread(new ThreadStart(Method));
                    thread.Start();
                    richSend.Clear();
                    int pageIndex = xtraTabControl1.SelectedTabPageIndex;
                    if (pageIndex == 0)
                    {
                        if (gridView2.DataSource != null && gridView2.Rows.Count > 0)
                        {
                            strMsgID = gridView2.GetFocusedRowCellValue("ID").ToString();
                            strUsersNickName = gridView2.GetFocusedRowCellValue("UsersNickName").ToString();
                        }
                    }
                    else
                    {
                        if (gridView1.DataSource != null && gridView1.Rows.Count > 0)
                        {
                            strMsgID = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ID").ToSafeString();
                            strUsersNickName = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "UsersNickName").ToSafeString();
                        }
                    }
                    BoundReplyList();
                    BoundMsgList("");
                }
                catch
                {
                    strMsgID = "";
                    strUsersNickName = "";
                    richHistory.Clear();
                }
            }
        }
        #region 查询事件（已回复列表）
        private void btnQuery_Click(object sender, EventArgs e)
        {
            BindReply();
        }
        private void BindReply()
        {
            strMsgID = string.Empty;
            strUsersNickName = string.Empty;
            DataTable dt = service.GetRepliedProblemTable("", chkTopic.Checked.ToSafeString().ToLower(), "", "", "", txtMsgTitle.Text.Trim(), txtMsgUsersNickName.Text);
            if (dt != null)
            {
                dt.Columns.Add("strNO", typeof(int));
                for (int i = 1; i <= dt.Rows.Count; i++)
                {
                    dt.Rows[i - 1]["strNO"] = i;
                }
                strMsgID = dt.Rows[0]["ID"].ToString().Trim();
                strUsersNickName = dt.Rows[0]["UsersNickName"].ToString().Trim();
                BoundReplyList();
            }
            dgvDisplayReply.DataSource = dt;
        }

        #endregion
        #region 查询条件（待回复列表）
        private void checkIsTop_CheckedChanged(object sender, EventArgs e)
        {
            string strCondition = "";

            BoundMsgList(strCondition);
        }

        private void ckStudent_CheckedChanged(object sender, EventArgs e)
        {
            string strCondition = "";

            BoundMsgList(strCondition);
        }

        private void ckIsFee_CheckedChanged(object sender, EventArgs e)
        {
            string strCondition = "";

            BoundMsgList(strCondition);
        }

        private void ConsultResorce_EditValueChanged(object sender, EventArgs e)
        {
            string strCondition = "";

            BoundMsgList(strCondition);
        }
        #endregion

        #region 待回复区鼠标右键事件
        private void cSPrivate_Click(object sender, EventArgs e)
        {
            string strID = gridView2.GetRowCellValue(gridView2.FocusedRowHandle, "ID").ToSafeString();
            bool flag = service.UpdateIsPublic(strID, "0");
            if (flag)
            {
                gridView2.SetRowCellValue(gridView2.FocusedRowHandle, "IsPublic", "不公开");
            }
            else
            {
                DevHelper.ShowErrorMessageBox("设置失败！");
            }
        }

        private void cSDelete_Click(object sender, EventArgs e)
        {
            string strID = gridView2.GetRowCellValue(gridView2.FocusedRowHandle, "ID").ToSafeString();
            bool flag = service.DeleteConsultTitle(strID);
            if (flag)
            {
                BoundMsgList("");
            }
            else
            {
                DevHelper.ShowErrorMessageBox("删除失败！");
            }
        }

        private void cSTop_Click(object sender, EventArgs e)
        {
            string strID = gridView2.GetRowCellValue(gridView2.FocusedRowHandle, "ID").ToSafeString();
            bool flag = service.UpdateIsTop(strID, "1");
            if (flag)
            {
                BoundMsgList("");
            }
            else
            {
                DevHelper.ShowErrorMessageBox("设置失败！");
            }
        }

        private void cSNoTop_Click(object sender, EventArgs e)
        {
            string strID = gridView2.GetRowCellValue(gridView2.FocusedRowHandle, "ID").ToSafeString();
            bool flag = service.UpdateIsTop(strID, "0");
            if (flag)
            {
                BoundMsgList("");
            }
            else
            {
                DevHelper.ShowErrorMessageBox("设置失败！");
            }
        }

        private void cSPublic_Click(object sender, EventArgs e)
        {
            string strID = gridView2.GetRowCellValue(gridView2.FocusedRowHandle, "ID").ToSafeString();
            bool flag = service.UpdateIsPublic(strID, "1");
            if (flag)
            {
                gridView2.SetRowCellValue(gridView2.FocusedRowHandle, "IsPublic", "公开");
            }
            else
            {
                DevHelper.ShowErrorMessageBox("设置失败！");
            }
        }
        #endregion

        #region 回复区鼠标右键事件
        private void cs_hf_TOP_Click(object sender, EventArgs e)
        {
            string strID = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ID").ToSafeString();
            bool flag = service.UpdateIsTop(strID, "1");
            if (flag)
            {
                BindReply();
            }
            else
            {
                DevHelper.ShowErrorMessageBox("设置失败！");
            }
        }

        private void cs_hf_TOP_QX_Click(object sender, EventArgs e)
        {
            string strID = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ID").ToSafeString();
            bool flag = service.UpdateIsTop(strID, "0");
            if (flag)
            {
                BindReply();
            }
            else
            {
                DevHelper.ShowErrorMessageBox("设置失败！");
            }
        }

        private void cs_hf_Public_Click(object sender, EventArgs e)
        {
            string strID = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ID").ToSafeString();
            bool flag = service.UpdateIsPublic(strID, "1");
            if (flag)
            {
                BindReply();
            }
            else
            {
                DevHelper.ShowErrorMessageBox("设置失败！");
            }
        }

        private void cs_hf_Public_QX_Click(object sender, EventArgs e)
        {
            string strID = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ID").ToSafeString();
            bool flag = service.UpdateIsPublic(strID, "0");
            if (flag)
            {
                BindReply();
            }
            else
            {
                DevHelper.ShowErrorMessageBox("设置失败！");
            }
        }

        private void cs_hf_Delete_Click(object sender, EventArgs e)
        {
            string strID = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ID").ToSafeString();
            bool flag = service.DeleteConsultTitle(strID);
            if (flag)
            {
                BindReply();
            }
            else
            {
                DevHelper.ShowErrorMessageBox("删除失败！");
            }
        }
        #endregion

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            if (gridView1.GetFocusedValue() != null)
            {
                strMsgID = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ID").ToSafeString();
                strUsersNickName = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "UsersNickName").ToSafeString();
                BoundReplyList();
            }
        }

        private void gridView2_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            if (gridView2.GetFocusedValue() != null)
            {
                strMsgID = gridView2.GetRowCellValue(gridView2.FocusedRowHandle, "ID").ToSafeString();
                strUsersNickName = gridView2.GetRowCellValue(gridView2.FocusedRowHandle, "UsersNickName").ToSafeString();
                BoundReplyList();
            }
        }

        private void timer_ReadID_Tick(object sender, EventArgs e)
        {
            BoundMsgList(string.Empty);
        }

        private void ConsultForm_List_FormClosed(object sender, FormClosedEventArgs e)
        {
            timer_ReadID.Enabled = false;
        }

        private void gridView2_DoubleClick(object sender, EventArgs e)
        {
            if (gridView2.GetFocusedValue() != null)
            {
                DataTable dt = service.GetConsultTitleByID(gridView2.GetRowCellValue(gridView2.FocusedRowHandle, "ID").ToSafeString());
                if (dt != null)
                {
                    if (dt.Rows[0]["UserType"].ToString() == "考生")
                    {
                        TB_SignUpStudents model = new ServiceExaminee().GetExameeByID(dt.Rows[0]["NickName"].ToString());
                        if (model != null)
                        {
                            Examinee_ExameeDetailForm obj = new Examinee_ExameeDetailForm();
                            obj.strNMT_SignUpID = model.NMT_SignUpID;
                            obj.strSignUpID = model.SignUpID;
                            obj.Run();
                        }
                    }
                }
            }
        }

        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            if (gridView1.GetFocusedValue() != null)
            {
                DataTable dt = service.GetConsultTitleByID(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ID").ToSafeString());
                if (dt != null)
                {
                    if (dt.Rows[0]["UserType"].ToString() == "考生")
                    {
                        TB_SignUpStudents model = new ServiceExaminee().GetExameeByID(dt.Rows[0]["NickName"].ToString());
                        if (model != null)
                        {
                            Examinee_ExameeDetailForm obj = new Examinee_ExameeDetailForm();
                            obj.strNMT_SignUpID = model.NMT_SignUpID;
                            obj.strSignUpID = model.SignUpID;
                            obj.Run();
                        }
                    }
                }
            }
        }
    }
}
